﻿<template>
  <div class="problems-container">
    <!-- 页面头部 -->
    <div class="problems-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="main-title">算法题库</h1>
          <p class="subtitle">精选编程题目，提升算法思维与编程能力</p>
        </div>
        <div class="stats-section">
          <div class="stat-item">
            <div class="stat-value">{{ total }}</div>
            <div class="stat-label">题目总数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value solved">{{ solvedCount }}</div>
            <div class="stat-label">已完成</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ Math.round((solvedCount / total) * 100) || 0 }}%</div>
            <div class="stat-label">完成率</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选工具栏 -->
    <div class="filter-toolbar">
      <div class="toolbar-left">
        <el-input v-model="searchForm.keyword" placeholder="搜索题目..." prefix-icon="Search" clearable class="search-input" @input="handleSearch" />
        <el-select v-model="searchForm.difficulty" placeholder="难度" clearable class="filter-select" @change="handleFilterChange">
          <el-option label="简单" value="easy" />
          <el-option label="中等" value="medium" />
          <el-option label="困难" value="hard" />
        </el-select>
        <el-select v-model="searchForm.status" placeholder="状态" clearable class="filter-select" @change="handleFilterChange">
          <el-option label="已完成" value="solved" />
          <el-option label="未完成" value="unsolved" />
          <el-option label="已尝试" value="attempted" />
        </el-select>
      </div>
      <div class="toolbar-right">
        <el-button-group>
          <el-button :type="viewMode === 'list' ? 'primary' : ''" :icon="List" @click="viewMode = 'list'">列表</el-button>
          <el-button :type="viewMode === 'card' ? 'primary' : ''" :icon="Grid" @click="viewMode = 'card'">卡片</el-button>
        </el-button-group>
      </div>
    </div>
    <!-- 题目列表 -->
    <div class="problems-content" v-loading="loading">
      <!-- 列表视图 -->
      <div v-if="viewMode === 'list'" class="list-view">
        <!-- 空数据状态 -->
        <div v-if="!loading && problemList.length === 0" class="empty-state">
          <div class="empty-content">
            <h3>暂无题目数据</h3>
            <p>请稍后再试或联系管理员</p>
            <el-button type="primary" @click="fetchProblems">重新加载</el-button>
          </div>
        </div>

        <el-table v-else :data="problemList" class="problems-table" @row-click="handleProblemClick" row-class-name="problem-row">
          <el-table-column width="60" align="center">
            <template #default="{ row }">
              <div class="status-indicator">
                <el-icon v-if="row.solved" class="solved-icon"><Check /></el-icon>
                <el-icon v-else-if="row.attempted" class="attempted-icon"><Clock /></el-icon>
                <div v-else class="unsolved-dot"></div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="id" label="#" width="80" align="center" />
          <el-table-column prop="title" label="题目" min-width="300">
            <template #default="{ row }">
              <div class="problem-title-cell">
                <span class="title-text">{{ row.title }}</span>
                <div class="tags">
                  <el-tag v-for="tag in row.tags" :key="tag" size="small" type="info" effect="plain">
                    {{ tag }}
                  </el-tag>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="difficulty" label="难度" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getDifficultyType(row.difficulty)" size="small" effect="light">
                {{ getDifficultyText(row.difficulty) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="acceptanceRate" label="通过率" width="100" align="center">
            <template #default="{ row }">
              <span class="acceptance-rate">{{ row.acceptanceRate }}%</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click.stop="handleSolve(row)">
                {{ row.solved ? "再次挑战" : "开始解题" }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 卡片视图 -->
      <div v-else class="card-view">
        <!-- 空数据状态 -->
        <div v-if="!loading && problemList.length === 0" class="empty-state">
          <div class="empty-content">
            <h3>暂无题目数据</h3>
            <p>请稍后再试或联系管理员</p>
            <el-button type="primary" @click="fetchProblems">重新加载</el-button>
          </div>
        </div>

        <div v-else class="problems-grid">
          <div v-for="problem in problemList" :key="problem.id" class="problem-card" @click="handleProblemClick(problem)">
            <div class="card-header">
              <div class="problem-status">
                <el-icon v-if="problem.solved" class="solved-icon"><Check /></el-icon>
                <el-icon v-else-if="problem.attempted" class="attempted-icon"><Clock /></el-icon>
                <div v-else class="unsolved-dot"></div>
              </div>
              <div class="problem-id">#{{ problem.id }}</div>
            </div>
            <div class="card-body">
              <h3 class="problem-title">{{ problem.title }}</h3>
              <div class="problem-meta">
                <el-tag :type="getDifficultyType(problem.difficulty)" size="small" effect="light">
                  {{ getDifficultyText(problem.difficulty) }}
                </el-tag>
                <span class="acceptance-rate">{{ problem.acceptanceRate }}% 通过</span>
              </div>
              <div class="problem-tags">
                <el-tag v-for="tag in problem.tags.slice(0, 3)" :key="tag" size="small" type="info" effect="plain">
                  {{ tag }}
                </el-tag>
              </div>
            </div>
            <div class="card-footer">
              <el-button type="primary" size="small" @click.stop="handleSolve(problem)">
                {{ problem.solved ? "再次挑战" : "开始解题" }}
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[12, 24, 48, 96]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from "vue"
import { useRouter } from "vue-router"
import { ElMessage } from "element-plus"
import { Check, Clock, Grid, List } from "@element-plus/icons-vue"
import { useProblemsStore } from "@/stores/modules/problem"
import { getDifficultyText, getDifficultyType, mapDifficultyToBackend, mapDifficultyToFrontend } from "@/utils/business/problem/difficulty"
import { calculateAcceptanceRate } from "@/utils/business/problem/status"

const router = useRouter()
const problemsStore = useProblemsStore()

// 响应式数据
const currentPage = ref(1)
const pageSize = ref(12)
const viewMode = ref("list")
// 从 store获取数据
const loading = computed(() => problemsStore.loading)
const problemList = computed(() => {
  if (!Array.isArray(problemsStore.problems)) {
    return []
  }
  return problemsStore.problems.map(problem => ({
    ...problem,
    difficulty: mapDifficultyToFrontend(problem.difficulty) || "easy",
    acceptanceRate: problem.acceptanceRate || calculateAcceptanceRate(problem.acceptedCount, problem.submissionCount),
    tags: problem.category ? [problem.category] : ["算法"],
    // 注意：用户提交状态需要后端提供用户提交记录API后实现
    // 当前设为false，避免显示错误的状态信息
    solved: problem.userStatus?.solved || false,
    attempted: problem.userStatus?.attempted || false
  }))
})
const total = computed(() => problemsStore.total)
const solvedCount = computed(() => problemList.value.filter(p => p.solved).length)

// 搜索表单
const searchForm = reactive({
  keyword: "",
  difficulty: "",
  status: ""
})

// 辅助方法已移至共享工具函数

// 获取题目列表
const fetchProblems = async () => {
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      title: searchForm.keyword,
      difficulty: mapDifficultyToBackend(searchForm.difficulty),
      isAdmin: false // 普通用户接口
    }

    await problemsStore.getProblemList(params)
  } catch (error) {
    ElMessage.error("获取题目列表失败，请稍后重试")
  }
}

// 难度映射和通过率计算函数已移至共享工具函数

// 事件处理
const handleSearch = () => {
  currentPage.value = 1
  fetchProblems()
}

const handleFilterChange = () => {
  currentPage.value = 1
  fetchProblems()
}

const handleProblemClick = problem => {
  router.push(`/problem/${problem.id}`)
}

const handleSolve = problem => {
  router.push(`/problem/solve/${problem.id}`)
}

const handleSizeChange = size => {
  pageSize.value = size
  currentPage.value = 1
  fetchProblems()
}

const handleCurrentChange = page => {
  currentPage.value = page
  fetchProblems()
}

// 初始化
onMounted(() => {
  fetchProblems()
})
</script>

<style lang="scss" scoped>
@use "@/styles/base/variables" as *;
@use "@/styles/base/mixins" as *;

.problems-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
  background: $bg-color-layout;
  min-height: 100vh;
}

// 页面头部
.problems-header {
  @include theme-card;
  background: linear-gradient(135deg, $color-primary-light-9, $bg-color-white);
  border-radius: 16px;
  padding: 32px;
  margin-bottom: 24px;
  color: $color-text-primary;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title-section {
      .main-title {
        font-size: 32px;
        font-weight: 700;
        margin: 0 0 8px 0;
      }

      .subtitle {
        font-size: 16px;
        opacity: 0.9;
        margin: 0;
      }
    }

    .stats-section {
      display: flex;
      gap: 32px;

      .stat-item {
        text-align: center;

        .stat-value {
          font-size: 28px;
          font-weight: 700;
          margin-bottom: 4px;
          color: $color-text-primary;

          &.solved {
            color: $color-success;
          }
        }

        .stat-label {
          font-size: 14px;
          color: $color-text-secondary;
        }
      }
    }
  }
}

// 筛选工具栏
.filter-toolbar {
  @include theme-card;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .toolbar-left {
    display: flex;
    gap: 16px;
    align-items: center;

    .search-input {
      width: 300px;
    }

    .filter-select {
      width: 120px;
    }
  }
}

// 题目列表
.problems-content {
  @include theme-card;
  border-radius: 12px;
  overflow: hidden;
}

// 列表视图
.list-view {
  .problems-table {
    :deep(.el-table__header) {
      background: #f8fafc;
    }

    :deep(.problem-row) {
      cursor: pointer;
      transition: background-color 0.2s;

      &:hover {
        background: #f1f5f9;
      }
    }

    .status-indicator {
      display: flex;
      justify-content: center;

      .solved-icon {
        color: #10b981;
        font-size: 18px;
      }

      .attempted-icon {
        color: #f59e0b;
        font-size: 18px;
      }

      .unsolved-dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #d1d5db;
      }
    }

    .problem-title-cell {
      .title-text {
        font-weight: 600;
        color: #1f2937;
        margin-bottom: 4px;
        display: block;
      }

      .tags {
        display: flex;
        gap: 4px;
        flex-wrap: wrap;
      }
    }

    .acceptance-rate {
      font-weight: 600;
    }
  }
}

// 卡片视图
.card-view {
  padding: 24px;

  .problems-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 20px;

    .problem-card {
      @include theme-card;
      border-radius: 12px;
      padding: 20px;
      cursor: pointer;
      transition: all 0.2s;

      &:hover {
        border-color: $color-primary;
        box-shadow: $box-shadow-base;
        transform: translateY(-2px);
      }

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        .problem-status {
          .solved-icon {
            color: #10b981;
            font-size: 20px;
          }

          .attempted-icon {
            color: #f59e0b;
            font-size: 20px;
          }

          .unsolved-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: #d1d5db;
          }
        }

        .problem-id {
          font-size: 14px;
          color: #6b7280;
          font-weight: 600;
        }
      }

      .card-body {
        .problem-title {
          font-size: 18px;
          font-weight: 600;
          color: #1f2937;
          margin: 0 0 12px 0;
          line-height: 1.4;
        }

        .problem-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;

          .acceptance-rate {
            font-size: 14px;
            color: #6b7280;
          }
        }

        .problem-tags {
          display: flex;
          gap: 6px;
          flex-wrap: wrap;
          margin-bottom: 16px;
        }
      }

      .card-footer {
        display: flex;
        justify-content: flex-end;
      }
    }
  }
}

// 分页
.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 24px;
  background: $bg-color-white;
  border-top: 1px solid $border-color-lighter;
}

// 空数据状态
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  padding: 40px;

  .empty-content {
    text-align: center;
    color: #6b7280;

    .empty-icon {
      font-size: 64px;
      margin-bottom: 16px;
    }

    h3 {
      font-size: 20px;
      font-weight: 600;
      margin: 0 0 8px 0;
      color: #374151;
    }

    p {
      font-size: 14px;
      margin: 0 0 24px 0;
      color: #9ca3af;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .problems-container {
    padding: 16px;
  }

  .problems-header {
    padding: 24px 20px;

    .header-content {
      flex-direction: column;
      gap: 20px;
      text-align: center;

      .stats-section {
        gap: 20px;
      }
    }
  }

  .filter-toolbar {
    flex-direction: column;
    gap: 16px;

    .toolbar-left {
      width: 100%;
      flex-wrap: wrap;

      .search-input {
        width: 100%;
      }
    }
  }

  .card-view .problems-grid {
    grid-template-columns: 1fr;
  }
}
</style>
